package com.tiza.xiaoyoubao.ui.fragment;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.tianze.library.base.BaseFragment;
import com.tiza.xiaoyoubao.R;
import com.tiza.xiaoyoubao.app.Constants;
import com.tiza.xiaoyoubao.app.UIHelper;
import com.tiza.xiaoyoubao.entity.IdCardInfo;
import com.tiza.xiaoyoubao.entity.UserInfo;
import com.tiza.xiaoyoubao.net.ApiHttpClient;
import com.tiza.xiaoyoubao.net.JsonCallback;
import com.tiza.xiaoyoubao.net.ResponseInfo;
import com.tiza.xiaoyoubao.utils.ImageUtils;

import org.simple.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;

import static android.app.Activity.RESULT_OK;

/**
 * Created by mapple on 17/3/15.
 * 身份证认证信息
 */

public class IDCertificationFragment extends BaseFragment {

    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.iv_idCard)
    ImageView iv_idCard;
    @BindView(R.id.tv_auditState)
    TextView tv_auditState;
    @BindView(R.id.tv_userName)
    TextView tv_userName;
    @BindView(R.id.view_upLoad)
    View view_upLoad;
    @BindView(R.id.view_certified)
    View view_certified;

    private File imageFile;
    private Bitmap bitmap1;
    private String buyerName;
    IdCardInfo idCardInfo;
    UserInfo userInfo = Hawk.get(Constants.KEY_USER_INFO, (UserInfo) null);
    /**
     * 选择图片的返回码
     */
    public final static int SELECT_IMAGE_RESULT_CODE = 200;
    String[] proj = {MediaStore.MediaColumns.DATA};
    /**
     * 当前选择的图片的路径
     */
    public String mImagePath;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        idCardInfo = (IdCardInfo) args.getSerializable("info");
        //        if (null == idCardInfo) {
        //            toast("详情加载失败");
        //            finish();
        //        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_id_certification;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        if (idCardInfo != null) {
            if (idCardInfo.getAuth().equals("2")) {
                view_upLoad.setVisibility(View.VISIBLE);
                view_certified.setVisibility(View.GONE);
            } else {
                view_upLoad.setVisibility(View.GONE);
                view_certified.setVisibility(View.VISIBLE);
                tv_userName.setText("姓名：" + idCardInfo.getRealname());
                if (idCardInfo.getAuth().equals("1")) {
                    tv_auditState.setText("审核状态:审核通过");
                } else if (idCardInfo.getAuth().equals("0")) {
                    tv_auditState.setText("审核状态:审核中");
                }
            }

        } else {
            view_upLoad.setVisibility(View.VISIBLE);
            view_certified.setVisibility(View.GONE);
        }
        intWatch();
    }

    @OnClick({R.id.btn_check, R.id.view_idCard, R.id.btn_save})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_check:
                UIHelper.showIdCardRule(mActivity);
                break;
            case R.id.view_idCard:
                takePhoto();
                break;
            case R.id.btn_save:
                buyerName = et_name.getText().toString().trim();
                if (imageFile == null || TextUtils.isEmpty(buyerName)) {
                    toast("请将资料填写完整");
                } else {
                    setBuyerIdCard();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_IMAGE_RESULT_CODE && resultCode == RESULT_OK) {
            String imagePath = "";
            Uri uri = null;
            if (data != null && data.getData() != null) {// 有数据返回直接使用返回的图片地址
                uri = data.getData();
                Cursor cursor = getActivity().getContentResolver().query(uri, proj, null, null,
                                                                         null
                );
                if (cursor == null) {
                    uri = ImageUtils.getUri(getActivity(), data);
                }
                imagePath = ImageUtils.getFilePathByFileUri(getActivity(), uri);
            } else {// 无数据使用指定的图片路径
                imagePath = mImagePath;
                int i = ImageUtils.parseImageDegree(imagePath);
                System.out.println("旋转的角度:" + i);

            }
            //获取图片缩略图，避免OOM
            Bitmap bitmap = ImageUtils.getImageThumbnail(imagePath, ImageUtils.getWidth(
                    getActivity().getApplicationContext()) / 3 - 5, ImageUtils.getWidth(
                    getActivity().getApplicationContext()) / 3 - 5);
            bitmap1 = ImageUtils.rotateBitmap(bitmap, ImageUtils.parseImageDegree(imagePath));
            iv_idCard.setImageBitmap(bitmap1);
        }
    }

    /***
     * 从相册中取图片
     */
    public void pickPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        getActivity().startActivityForResult(intent, SELECT_IMAGE_RESULT_CODE);
    }

    /**
     * 拍照获取图片
     */
    @RequiresApi(api = Build.VERSION_CODES.FROYO)
    public void takePhoto() {
        // 执行拍照前，应该先判断SD卡是否存在
        String SDState = Environment.getExternalStorageState();
        if (SDState.equals(Environment.MEDIA_MOUNTED)) {
            /**
             * 通过指定图片存储路径，解决部分机型onActivityResult回调 data返回为null的情况
             */
            //获取与应用相关联的路径
            String imageFilePath = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
                                                .getAbsolutePath();
            //SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
            //根据当前时间生成图片的名称
            String timestamp = "/" + "idCard" + ".jpg";
            imageFile = new File(imageFilePath, timestamp);// 通过路径创建保存文件
            if (imageFile.exists()) {
                imageFile.delete();
                imageFile = new File(imageFilePath, timestamp);// 通过路径创建保存文件
            }
            mImagePath = imageFile.getAbsolutePath();
            Uri imageFileUri = Uri.fromFile(imageFile);// 获取文件的Uri
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);// 告诉相机拍摄完毕输出图片到指定的Uri
            getActivity().startActivityForResult(intent, SELECT_IMAGE_RESULT_CODE);
        } else {
            toast("内存卡不存在");
        }
    }


    private void setBuyerIdCard() {
        ApiHttpClient.setBuyerIdCard(this, buyerName, imageFile,
                                     userInfo.getWebzzCmsBuyerInfo().getUserid(),
                                     new JsonCallback<IdCardInfo>(IdCardInfo.class) {

                                         @Override
                                         public void onBefore(Request request) {
                                             super.onBefore(request);
                                             showWaitingDialog();
                                         }

                                         @Override
                                         public void onError(Call call, Exception e) {
                                             toast("网络异常，请检查后再试");
                                         }

                                         @Override
                                         public void onResponse(ResponseInfo<IdCardInfo> response) {
                                             int code = response.getCode();
                                             if (code == 1) {
                                                 showWarnDialog(response.getMessage());
                                                 return;
                                             }
                                             toast("身份证绑定成功");
                                             // 通知登录成功
                                             EventBus.getDefault().post(true,
                                                                        Constants.TAG_SET_BUYERIDCARD_SUCCESS
                                             );
                                             finish();
                                         }

                                         @Override
                                         public void onAfter() {
                                             super.onAfter();
                                             hideWaitingDialog();
                                         }
                                     }
        );
    }

    public void intWatch() {
        et_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                et_name.setTextColor(getResources().getColor(R.color.textColorThird));
            }
        });

    }
}
